/*
 *      Author: Guannan Ma
 *      @mythmgn
 *      Whatever license applied
 */

#include <string.h>
#include <fcntl.h>

#include "base.h"

strSplit* initToken(char *p_delimiter) {

	strSplit *p_ss=(strSplit*)malloc(sizeof(strSplit));

    ASSERT(p_delimiter!=NULL);

    if(NULL==p_ss){
        setErrStatusCode(MEMORY_MALLOC_FAILURE);
        return NULL;
    }

    p_ss->pos=0;
    p_ss->delimiter=(char *)malloc(sizeof(char)*strlen(p_delimiter)+1);
    if(NULL==p_ss->delimiter){
        setErrStatusCode(MEMORY_MALLOC_FAILURE);
        return NULL;
    }
    strcpy(p_ss->delimiter,p_delimiter);
    p_ss->delimiter[strlen(p_delimiter)]='\0';

    p_ss->splitStr=NULL;

    return p_ss;
}

BOOL closeToken(strSplit *p_ss) {
    ASSERT(p_ss!=NULL);

    FREEUP(p_ss->delimiter);
    FREEUP(p_ss->splitStr);

    FREEUP(p_ss);
    return TRUE;
}

BOOL getSplitString(char *src,strSplit *p_ss) {

    int nextPos;
    int i;
    ASSERT(p_ss!=NULL);

    if(p_ss->splitStr)
        memset(p_ss->splitStr,'\0',strlen(p_ss->splitStr));

    if(p_ss->pos-1==strlen(src))
        return FALSE;

    for(nextPos=p_ss->pos; nextPos<=strlen(src); nextPos++) {
        for(i=0; p_ss->delimiter[i]&&src[nextPos]; i++) {
            if(p_ss->delimiter[i]==src[nextPos]) {
                nextPos++;
                goto jump_to;
            }
        }
    }


jump_to:

    p_ss->splitStr=(char*)realloc(p_ss->splitStr,(nextPos-(p_ss->pos))*sizeof(char));
    if(!p_ss->splitStr){
        setErrStatusCode(MEMORY_MALLOC_FAILURE);
        return FALSE;
    }
    strncpy(p_ss->splitStr,src+p_ss->pos,(nextPos-(p_ss->pos)-1));
    p_ss->splitStr[nextPos-(p_ss->pos)-1]='\0';
    p_ss->pos=nextPos;
    return TRUE;

}

BOOL setNonBlockingFD(int fd){
	if(fd<0||0==fd||(-1==fcntl(fd,F_SETFL,fcntl(fd,F_GETFL,0)|O_NONBLOCK))){
		return FALSE;
	}else
		return TRUE;
}
